package com.wejoy.video.middle.station.admin.controller.file;

import com.wejoy.video.middle.station.admin.controller.BaseController;
import com.wejoy.video.middle.station.data.enums.file.EnumUpload;
import com.wejoy.video.middle.station.data.exception.BusinessException;
import com.wejoy.video.middle.station.data.service.file.IFileService;
import com.wejoy.video.middle.station.data.util.FileUtils;
import com.wejoy.video.middle.station.data.util.WJAssert;
import com.wejoy.video.middle.station.data.vo.RespJSON;
import com.wejoy.video.middle.station.data.vo.file.UploadFileVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;

/**
 * 公共文件上传接口
 *
 * @author admin
 */
@RestController
@RequestMapping("/file/upload")
public class UploadController extends BaseController {
    @Autowired
    private IFileService fileService;

    /**
     * 公司文件上传接口
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public RespJSON upload(String uploadItem, @RequestParam("file") MultipartFile file) {
        if (null == file) {
            throw new BusinessException("文件不合法");
        }
        String filename = file.getOriginalFilename();
        EnumUpload enumUploadItem = EnumUpload.getEnum(uploadItem);
        if (enumUploadItem == null) {
            throw new BusinessException("上传文件类目不正确");
        }
        try {
            Path tempFile = Files.createTempFile("tmp", filename);
            file.transferTo(tempFile);
            byte[] bytes = Files.readAllBytes(tempFile);
            UploadFileVO uploadResult = fileService.upload(enumUploadItem, bytes);
            uploadResult.setFileName(FileUtils.getFileNameWithoutSuffix(filename));

            if (filename.contains(".gif") || filename.contains(".gif")) {
                uploadResult.setSuffix("gif");
            }
            if (filename.contains(".svg") || filename.contains(".svga")) {
                uploadResult.setFileSize(uploadResult.getFileSize() == null ? 0 : uploadResult.getFileSize());
                uploadResult.setWidth(uploadResult.getWidth() == null ? 0 : uploadResult.getWidth());
                uploadResult.setHeight(uploadResult.getHeight() == null ? 0 : uploadResult.getHeight());
            }
            if (filename.contains(".png") || filename.contains(".png")) {
                uploadResult.setSuffix("png");
            }
            if (filename.contains(".jpg") || filename.contains(".jpg")) {
                uploadResult.setSuffix("jpg");
            }
            if (filename.contains(".jpeg") || filename.contains(".jpeg")) {
                uploadResult.setSuffix("jpeg");
            }
            return RespJSON.success(uploadResult);
        } catch (Exception e) {
            logger.error("文件上传错误", e);
            throw new BusinessException("文件上传错误");
        }
    }

    /**
     * 公司文件上传接口
     *
     * @param file
     * @return
     */
    @PostMapping("/uploadVideo")
    public RespJSON uploadVideo(@RequestParam("file") MultipartFile file) {
        String uploadItem = "resVideoLib";
        if (null == file) {
            throw new BusinessException("文件不合法");
        }
        String filename = file.getOriginalFilename();
        EnumUpload enumUploadItem = EnumUpload.getEnum(uploadItem);
        if (enumUploadItem == null) {
            throw new BusinessException("上传文件类目不正确");
        }
        try {
            Path tempFile = Files.createTempFile("tmp", filename);
            file.transferTo(tempFile);
            byte[] bytes = Files.readAllBytes(tempFile);
            UploadFileVO uploadResult = fileService.upload(enumUploadItem, bytes);
            uploadResult.setFileName(FileUtils.getFileNameWithoutSuffix(filename));

            if (filename.contains(".gif") || filename.contains(".gif")) {
                uploadResult.setSuffix("gif");
            }
            if (filename.contains(".svg") || filename.contains(".svga")) {
                uploadResult.setFileSize(uploadResult.getFileSize() == null ? 0 : uploadResult.getFileSize());
                uploadResult.setWidth(uploadResult.getWidth() == null ? 0 : uploadResult.getWidth());
                uploadResult.setHeight(uploadResult.getHeight() == null ? 0 : uploadResult.getHeight());
            }
            if (filename.contains(".png") || filename.contains(".png")) {
                uploadResult.setSuffix("png");
            }
            if (filename.contains(".mp4") || filename.contains(".mp4")){
                uploadResult.setFileSize((long) bytes.length);
            }
            return RespJSON.success(uploadResult);
        } catch (Exception e) {
            logger.error("文件上传错误", e);
            throw new BusinessException("文件上传错误");
        }
    }

    /**
     * base64上传图片
     *
     * @throws IOException
     */
    @RequestMapping("/uploadBase64")
    @ResponseBody
    public RespJSON uploadBase64(@RequestBody Map<String, String> map) throws Exception {
        String base64 = map.get("data");
        WJAssert.hasText(base64, "base64不能为空");
        if (base64.contains("data:")) {
            base64 = base64.substring(base64.indexOf(",") + 1);
        }
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] bytes = decoder.decodeBuffer(base64);
        UploadFileVO upload = fileService.upload(EnumUpload.RES_PHOTO_LIB, bytes);
        if (null == upload.getFileSize()) {
            upload.setFileSize((long) bytes.length);
        }
        // 获取文件后缀
        upload.setSuffix(getFileExtension(upload.getKey()));
        return RespJSON.success(upload);
    }

    private String getFileExtension(String fileName) {
        if (fileName == null) {
            return null;
        }
        int dotIndex = fileName.lastIndexOf('.');
        if (dotIndex >= 0) {
            // 返回最后一个点之后的部分作为扩展名
            return fileName.substring(dotIndex + 1);
        } else {
            // 没有扩展名
            return "";
        }
    }


    /**
     * URL上传图片
     *
     * @param map
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("/uploadUrl")
    @ResponseBody
    public RespJSON uploadUrl(@RequestBody Map<String, String> map) throws UnsupportedEncodingException {
        String url = map.get("url");
        url = URLDecoder.decode(url, "utf-8");
        String s = fileService.uploadFileByImgUrl(url, "");
        return RespJSON.success(s);
    }

    /**
     * 获得上传token
     *
     * @return
     */
    @RequestMapping("/getUploadToken")
    @ResponseBody
    public RespJSON uploadTokenByType() {
        String uploadToken = fileService.getUploadToken();
        return RespJSON.success(uploadToken);
    }

}
